package com.toby.day44.fragment;


import android.database.DataSetObserver;
import android.support.v4.app.Fragment;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.toby.day44.R;
import com.toby.day44.adapter.CarBusAdapter;
import com.toby.day44.bean.AppEntity;
import com.toby.day44.bean.Product;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.io.IOException;
import java.util.ArrayList;

/**
 * 文档  okhttp 框架 http://square.github.io/okhttp/2x/okhttp/
 */

@EFragment(R.layout.fragment_car)
public class CarFragment extends Fragment {
    private final String url = "http://nirvana.fruitday.com/api";
    @ViewById
    ListView carLv;
    @ViewById
    ImageView emptyImg;
    @ViewById
    TextView totalFee;
    @ViewById
    Button btnOrder;
    @ViewById
    LinearLayout carBuy;


    private CarBusAdapter adapter;
    private ArrayList<Product> list = new ArrayList<>();

    @AfterViews
    public void init() {
        initView();
        getData();
    }

    private void initView() {
        adapter = new CarBusAdapter(list, getActivity());
        adapter.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                totalFee.setText(String.valueOf(getSum()));
            }
        });
        carLv.setAdapter(adapter);
    }

    public int getSum() {
        int sum = 0;
        for (Product product : list) {
            sum += Float.valueOf(product.getPrice()) * product.getQty();
        }
        return sum;
    }

    /**
     *
     */
    private void loadData() {


        //get请求
        OkHttpClient httpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url("")
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {

            }
        });
//        post
        RequestBody body = new FormEncodingBuilder()
                .add("", "")
                .add("", "").build();

        Request postRequest = new Request.Builder()
                .url("")
                .post(body)
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                response.body().toString();

            }
        });


    }

    /**
     * sign=f0d2d568c50df4b87bc71cd4ef7eb8b3
     * &timestamp=1446033605
     * &platform=ANDROID
     * &source=app
     * &connect_id=f61b52a772a6627b31b4bf835930a82f
     * &region_id=143949
     * &service=cart.get
     * &device_id=ba36c4ad0755b970e1885bedd8a1f92d
     * &carttmp=
     * &channel=m360
     * &version=3.0.3
     *
     * sign=c1196be8f7fd45683268292c86d05d1a
     * &timestamp=1446035072
     * &platform=ANDROID
     * &source=app
     * &connect_id=f61b52a772a6627b31b4bf835930a82f
     * &region_id=143949
     * &service=cart.get
     * &device_id=ba36c4ad0755b970e1885bedd8a1f92d
     * &carttmp=
     * &channel=
     * m360
     * &version=3.0.3
     */
    private void initData() {
        OkHttpClient httpClient = new OkHttpClient();
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add("sign", "c1196be8f7fd45683268292c86d05d1a");
        builder.add("timestamp", "1446035072");
        builder.add("platform", "ANDROID");
        builder.add("source", "app");
        builder.add("connect_id", "f61b52a772a6627b31b4bf835930a82f");
        builder.add("region_id", "143949");
        builder.add("service", "cart.get");
        builder.add("device_id", "ba36c4ad0755b970e1885bedd8a1f92d");
        builder.add("carttmp", "");
        builder.add("channel", "m360");
        builder.add("version", "3.0.3");
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
//                AppEntity entity = JSONObject.parseObject(result, AppEntity.class);
//                list.addAll(entity.getCart().getItems());
//                adapter.notifyDataSetChanged();
            }
        });

    }


    private void getData() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("sign", "c1196be8f7fd45683268292c86d05d1a");
        params.addBodyParameter("timestamp", "1446035072");
        params.addBodyParameter("platform", "ANDROID");
        params.addBodyParameter("source", "app");
        params.addBodyParameter("connect_id", "f61b52a772a6627b31b4bf835930a82f");
        params.addBodyParameter("region_id", "143949");
        params.addBodyParameter("service", "cart.get");
        params.addBodyParameter("device_id", "ba36c4ad0755b970e1885bedd8a1f92d");
        params.addBodyParameter("carttmp", "");
        params.addBodyParameter("channel", "m360");
        params.addBodyParameter("version", "3.0.3");
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                AppEntity entity = JSONObject.parseObject(result, AppEntity.class);
                list.addAll(entity.getCart().getItems());
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }


}
